package org.fle4y.common.utils.basic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLException;

/**
 * author : xiehui<br>
 * company : northking <br>
 * Create at: 2012-6-26<br>
 * 
 * @version : 1.0<br>
 *          mailto:flexie@foxmail.com<br>
 *          Description :
 */
public class ByteArray {
	private byte data[];

	public ByteArray(String s) {
		data = StringConverter.hexToByte(s);
	}

	public ByteArray(byte[] a) {
		data = a;
	}

	public byte[] byteValue() {
		return data;
	}

	public int compareTo(ByteArray o) {
		int len = data.length;
		int lenb = o.data.length;

		for (int i = 0;; i++) {
			int a = 0, b = 0;

			if (i < len) {
				a = ((int) data[i]) & 0xff;
			} else if (i >= lenb) {
				return 0;
			}

			if (i < lenb) {
				b = ((int) o.data[i]) & 0xff;
			}

			if (a > b) {
				return 1;
			}

			if (b > a) {
				return -1;
			}
		}
	}

	public static byte[] serialize(Object s) throws SQLException {
		ByteArrayOutputStream bo = new ByteArrayOutputStream();

		try {
			ObjectOutputStream os = new ObjectOutputStream(bo);

			os.writeObject(s);

			return bo.toByteArray();
		} catch (Exception e) {
			throw new SQLException("序列化流发生错误");
		}
	}

	public static String serializeToString(Object s) throws SQLException {
		return createString(serialize(s));
	}

	public Object deserialize() throws SQLException {
		try {
			ByteArrayInputStream bi = new ByteArrayInputStream(data);
			ObjectInputStream is = new ObjectInputStream(bi);

			return is.readObject();
		} catch (Exception e) {
			throw new SQLException("序列化流发生错误 ！");
		}
	}

	public static String createString(byte b[]) {
		return StringConverter.byteToHex(b);
	}

	public String toString() {
		return createString(data);
	}

	public int hashCode() {
		return data.hashCode();
	}

}
